"""
文件处理模块
负责CSV文件的读取、解析和参数提取
"""

import os
import re
import pandas as pd
import numpy as np
import config


class FileHandler:
    """文件处理类，负责所有文件相关操作"""
    
    @staticmethod
    def read_file_parameters(file_path):
        """
        读取文件参数
        
        Args:
            file_path: 文件路径
            
        Returns:
            dict: 包含文件参数的字典，如果失败返回None
        """
        try:
            # 读取文件头部信息
            with open(file_path, 'r') as f:
                header_lines = [f.readline() for _ in range(config.CSV_HEADER_SKIP_ROWS)]
            
            # 解析参数
            params = {}
            for line in header_lines:
                if ':' in line:
                    parts = line.split(':', 1)
                    key = parts[0].strip()
                    value = parts[1].strip()
                    params[key] = value
            
            # 读取数据
            df = pd.read_csv(file_path, skiprows=config.CSV_HEADER_SKIP_ROWS)
            
            # 提取采样频率
            fs_mhz = float(config.DEFAULT_SAMPLING_FREQ)
            fs_str = params.get('Sample Rate', f'{config.DEFAULT_SAMPLING_FREQ}MHz')
            match = re.search(r'(\d*\.?\d+)', fs_str)
            if match:
                fs_mhz = float(match.group(1))
            
            sampling_freq = fs_mhz * 1e6
            
            # 计算时间范围
            num_points = len(df)
            t_max_us = num_points / sampling_freq * 1e6
            
            return {
                'filepath': file_path,
                'data_shape': df.shape,
                'parameters': params,
                'sampling_freq': sampling_freq,
                'fs_mhz': fs_mhz,
                't_max_us': t_max_us,
                'dataframe': df
            }
            
        except Exception as e:
            print(f"Error reading file parameters: {e}")
            return None
    
    @staticmethod
    def get_file_data(file_path):
        """
        获取文件数据
        
        Args:
            file_path: 文件路径
            
        Returns:
            tuple: (t, ADCs, ADCsorg, params, smplfreq, CMname) 或 (None, None, None, None, None, None)
        """
        try:
            # 读取文件参数
            file_params = FileHandler.read_file_parameters(file_path)
            if not file_params:
                return None, None, None, None, None, None
            
            df = file_params['dataframe']
            arr1 = df.to_numpy()
            
            # 处理复数数据
            r1, c1 = arr1.shape
            ch_num = c1 // 2
            ADCsorg = np.empty([r1, ch_num], dtype=complex)
            
            for k in range(ch_num):
                # 将幅度和相位转换为复数
                ADCsorg[:, k] = arr1[:, 2 * k] * np.exp(1j * arr1[:, 2 * k + 1] * np.pi / 180)
            
            # 生成时间轴
            smplfreq = file_params['sampling_freq']
            t = np.arange(r1) / smplfreq
            
            # 提取CM名称
            fname = os.path.basename(file_path)
            match = re.search(r'(CM\d-\d)', fname)
            CMname = match.group(1) if match else "Unknown"
            
            return t, arr1, ADCsorg, file_params['parameters'], smplfreq, CMname
            
        except Exception as e:
            print(f"Error getting file data: {e}")
            return None, None, None, None, None, None
    
    @staticmethod
    def create_preview_text(file_params):
        """
        创建预览文本
        
        Args:
            file_params: 文件参数字典
            
        Returns:
            str: 预览文本
        """
        if not file_params:
            return "无法读取文件参数"
        
        preview_text = f"文件: {os.path.basename(file_params['filepath'])}\n"
        preview_text += f"数据形状: {file_params['data_shape']}\n"
        preview_text += f"采样率: {file_params['sampling_freq'] / 1e6} MHz\n\n"
        preview_text += "头部参数:\n"
        
        for k, v in file_params['parameters'].items():
            preview_text += f"  - {k}: {v}\n"
            
        return preview_text
    
    @staticmethod
    def create_header(params, cm_name):
        """
        创建图表头部信息
        
        Args:
            params: 参数字典
            cm_name: CM名称
            
        Returns:
            str: 头部信息字符串
        """
        para_list = [
            params.get('File Name', '').replace('cm_rdy', cm_name),
            f"Sample Rate: {params.get('Sample Rate', 'N/A')}",
            f"Start Time: {params.get('Start Time', 'N/A')}",
            f"Cavity: {params.get('Cavity', 'N/A')}",
            f"V SET: {params.get('V SET', 'N/A')}",
            f"P SET: {params.get('P SET', 'N/A')}",
            f"MODE: {params.get('MODE', 'N/A')}",
            f"FB ON: {params.get('FB ON', 'N/A')}"
        ]
        return ' | '.join(para_list)
    
    @staticmethod
    def check_spurious(ADCsorg):
        """
        检查是否有虚假信号
        
        Args:
            ADCsorg: 复数数据数组
            
        Returns:
            bool: 是否检测到虚假信号
        """
        if ADCsorg is None or ADCsorg.shape[1] == 0:
            return False
        
        try:
            Pt = ADCsorg[:, 0]
            PtA = np.abs(Pt)
            PtAd = PtA[1:] - PtA[:-1]
            
            high_jumps = len(np.where(PtAd > config.SPURIOUS_THRESHOLD_HIGH)[0])
            low_jumps = len(np.where(PtAd < config.SPURIOUS_THRESHOLD_LOW)[0])
            
            return (high_jumps > 0 and low_jumps > 0) or \
                   (high_jumps + low_jumps > config.SPURIOUS_COUNT_THRESHOLD)
                   
        except Exception as e:
            print(f"Error checking spurious: {e}")
            return False 